﻿using UnityEngine;
using UnityEngine.SocialPlatforms;
using UnityEngine.UI;

namespace Framework
{
    public class UIFillLayer : UILayer
    {
        private RectTransform _transfLeft;
        private RectTransform _transfRight;
        private RectTransform _transfTop;
        private RectTransform _transfBottom;
        
        public UIFillLayer(string name, Transform root) : base(name, root)
        {
            _transfLeft = CreateFillObject("Left", new Vector2(0f, 0.5f), new Vector2(0f, 0f), new Vector2(0f, 1f), Vector2.zero, Vector2.zero);
            _transfRight = CreateFillObject("Right", new Vector2(1f, 0.5f), new Vector2(1f, 0f), new Vector2(1f, 1f), Vector2.zero, Vector2.zero);
            _transfTop = CreateFillObject("Top", new Vector2(0.5f, 1f), new Vector2(0f, 1f), new Vector2(1f, 1f), Vector2.zero, Vector2.zero);
            _transfBottom = CreateFillObject("Bottom", new Vector2(0.5f, 0f), new Vector2(0f, 0f), new Vector2(1f, 0f), Vector2.zero, Vector2.zero);
        }

        public override void SetFillWidth(float fillWidth, float width)
        {
            float halfWidth = fillWidth * 0.5f;
            Vector2 size = Global.Vec2;
            size.x = halfWidth;
            size.y = 0;
            _transfLeft.sizeDelta = size;
            _transfRight.sizeDelta = size;
        }

        public override void SetFillHeight(float fillHeight, float height)
        {
            float halfHeight = fillHeight * 0.5f;
            Vector2 size = Global.Vec2;
            size.x = 0;
            size.y = halfHeight;
            _transfTop.sizeDelta = size;
            _transfBottom.sizeDelta = size;
        }

        private RectTransform CreateFillObject(string name, Vector2 pivot, Vector2 anchorMin, Vector2 anchorMax, Vector2 offsetMin, Vector2 offsetMax)
        {
            GameObject gameObject = new GameObject(name, typeof(RectTransform), typeof(Image));
            Image image = gameObject.GetComponent<Image>();
            image.color = Color.black;
            RectTransform rectTransform = gameObject.transform as RectTransform;
            rectTransform.SetParent(_transform, false);
            rectTransform.pivot = pivot;
            rectTransform.anchorMin = anchorMin;
            rectTransform.anchorMax = anchorMax;
            rectTransform.offsetMin = offsetMin;
            rectTransform.offsetMax = offsetMax;
            return rectTransform;
        }
    }
}